﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.ComponentModel;
using System.Windows.Data;
using HugeFlow.CommandPattern.Interactivity;
using HugeFlow.CommandPattern.Commands;
using HugeFlow.Utility;

namespace HugeFlow.CommandPattern.Interactivity
{
    /// <summary>
    /// CommandName 으로 StaticCommand 를 엮어주는 Behavior.
    /// </summary>
    public class ExecuteStaticCommandBehavior : ExecuteCommandBehaviorBase
    {

        #region Properties

        [Category("Command")]
        public string CommandName
        {
            get { return _triggers.CommandName; }
            set
            {
                _triggers.CommandName = value;
            }
        }

        StaticCommandBinder _triggers = new StaticCommandBinder();
        public override ICommand CommandTriggers { get { return _triggers; } }

        #endregion Properties

        #region Methods

        protected override void OnAttached()
        {
            base.OnAttached();

            if (CommandName == null)
                throw new NullReferenceException(CommandPatternResource.NullCommand);

            if (AssociatedObject.IsInVisualTree() == false)
            {
                AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
                return;
            }

            if (CommandParameter != null)
            {
                _triggers.SetBinding(CommandBinderBase.InstantCommandParameterProperty, GetProperBinding(_triggers, CommandParameter));
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
            _triggers.ClearValue(FrameworkElement.DataContextProperty);
            _triggers.ClearValue(CommandBinderBase.InstantCommandParameterProperty);
            _triggers.CommandName = null;

            base.OnDetaching();
        }

        #endregion Methods

        #region EventHandlers

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);

            if (CommandParameter != null)
            {
                _triggers.SetBinding(CommandBinderBase.InstantCommandParameterProperty, GetProperBinding(_triggers, CommandParameter));
            }
        }

        #endregion EventHandlers
    }
}
